<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <li><a href="/home">首页</a></li>
  <li><a href="/about">关于</a></li>

  <div id="app"></div>


  <script>
    const routes = [
      {
        path: '/home',
        component: () => {
          return "<h1>首页页面</h1>"
        }
      },
      {
        path: '/about',
        component: () => {
          return "<h1>about页面</h1>"
        }
      },
    ]

    window.addEventListener('popstate', function () {   // 监听浏览器前进后退按钮
      routerView()
    })

    let linkList = document.querySelectorAll('a')
    linkList.forEach(link => {
      link.addEventListener('click', function (e) {
        // 让 a 标签不跳转
        e.preventDefault()   // 阻止默认行为
        // 让 url 发生变化
        // history.pushState(null, '', this.getAttribute('href'))
        history.pushState(null, '', this.getAttribute('href')) // 可以修改url，不会带来页面刷新   
        routerView()
      })
    })

    const app = document.getElementById('app')
    function routerView() {
      const index = routes.findIndex((item) => {
        return item.path === location.pathname
      })
      app.innerHTML = routes[index].component()
    }
  </script>
</body>

</html>